/*
 * @Author: zwf 240970521@qq.com
 * @Date: 2023-07-23 19:50:54
 * @LastEditors: zwf 240970521@qq.com
 * @LastEditTime: 2023-08-09 00:07:24
 * @FilePath: /esp32_motor/dataSensing/dataSensing.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "dataSensing.h"
#include "delay.h"
#include "driver/uart.h"
#include "pin.h"
#include "esp_log.h"
#include "motor_priv.h"

#define DATA_PORT_NUM      UART_NUM_2
#define DATA_PORT_SPEED    921600
#define DATA_TXD_PIN       19
#define DATA_RXD_PIN       18
#define DATA_TASK_SIZE     1024 * 4
#define DATA_TASK_PRIORITY 13
#define DATA_BUF_SIZE      1024

const static char *tag = "DATA SENSING";
TaskHandle_t       task;
QueueHandle_t      dataQueue;

/*数据发送线程*/
static void DATA_task(void *para)
{
    DataSendFrame sendFrame;

    while (1)
    {
        xQueueReceive(dataQueue, &sendFrame, portMAX_DELAY);
        sendFrame.buf[sendFrame.dataNum * 4 + 0] = 0x00;
        sendFrame.buf[sendFrame.dataNum * 4 + 1] = 0x00;
        sendFrame.buf[sendFrame.dataNum * 4 + 2] = 0x80;
        sendFrame.buf[sendFrame.dataNum * 4 + 3] = 0x7f;
        uart_write_bytes(DATA_PORT_NUM, &sendFrame, (sendFrame.dataNum+1)*4);
        // mdelay(2000);
    }
}

/*初始化*/
esp_err_t DATA_init(void)
{
    uart_config_t uartConfig = {
        .baud_rate  = DATA_PORT_SPEED,
        .data_bits  = UART_DATA_8_BITS,
        .parity     = UART_PARITY_DISABLE,
        .stop_bits  = UART_STOP_BITS_1,
        .flow_ctrl  = UART_HW_FLOWCTRL_DISABLE,
        .source_clk = UART_SCLK_DEFAULT,
    };

    if (PIN_register(DATA_TXD_PIN, PIN_TXD) || PIN_register(DATA_RXD_PIN, PIN_RXD))
    {
        ESP_LOGE(tag, "pin register error\n");
        return ESP_FAIL;
    }

    ESP_ERROR_CHECK(uart_driver_install(DATA_PORT_NUM, 256, DATA_BUF_SIZE * 2, 0, NULL, 0));
    ESP_ERROR_CHECK(uart_param_config(DATA_PORT_NUM, &uartConfig));
    ESP_ERROR_CHECK(uart_set_pin(DATA_PORT_NUM, DATA_TXD_PIN, DATA_RXD_PIN, -1, -1));

    dataQueue = xQueueCreate(10, sizeof(DataSendFrame));
    if (pdPASS != xTaskCreatePinnedToCore(DATA_task, tag, DATA_TASK_SIZE, NULL, DATA_TASK_PRIORITY, &task, 1))
    {
        ESP_LOGE(tag, "modbus_slave task create fail\n");
    }

    return ESP_OK;
}
